<template>
  <div>
    <textarea :id="id" />
  </div>
</template>

<script>
export default {
  name: 'JspCkeditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: 'content'
    },
    // 替换配置
    /**
     * 除ckeditor内置配置外，还支持以下自定义配置
     * {
     *  headers: {}, // 请求头设置
     *  filebrowserUploadInputName: 'file', // 上传字段名
     *  imageWater: true // 是否打水印
     * }
     *
     */
    config: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      ckeditor: null
    }
  },
  watch: {
    // 监听value变化
    value() {
      if (this.value !== this.ckeditor.getData()) {
        this.ckeditor.setData(this.value)
      }
    }
  },
  mounted() {
    // 挂载后：初始化对象、编辑器内容以及监听编辑器内容变化
    this.ckeditor = window.CKEDITOR.replace(this.id, this.config)
    this.ckeditor.setData(this.value)
    this.ckeditor.on('change', () =>
      this.$emit('input', this.ckeditor.getData())
    )
    // 上传请求头处理
    this.ckeditor.on('fileUploadRequest', (evt) => {
      var fileLoader = evt.data.fileLoader
      var formData = new FormData()
      var xhr = fileLoader.xhr
      xhr.open('POST', fileLoader.uploadUrl, true)
      formData.append(this.config.filebrowserUploadInputName ?? 'file', fileLoader.file, fileLoader.fileName)
      // 是否打水印
      if (this.config.water) {
        formData.append('water', true)
      }
      // 请求头设置
      if (this.config.headers) {
        for (var i in this.config.headers) {
          fileLoader.xhr.setRequestHeader(i, this.config.headers[i])
        }
      }
      fileLoader.xhr.send(formData)
      evt.stop()
    })
    // 上传响应处理
    this.ckeditor.on('fileUploadResponse', (evt) => {
    // Prevent the default response handler.
      evt.stop()
      /**
       * 后端响应数据结构
       * 成功：{"code":200,"message":"上传成功","data":[items:[{"id":136,"name":"1.png","ext":"png","size":209363,"path":"2022\/01\/05\/j02u13NSfrS1lXnF0vm2M8qrRsjVlROoMHy3Gbg9.png","url":"http:\/\/file.laravel8.com\/2022\/01\/05\/j02u13NSfrS1lXnF0vm2M8qrRsjVlROoMHy3Gbg9.png"}]]}
       * 失败：{"code":200,"message":"上传失败"}
       */
      var data = evt.data
      var xhr = data.fileLoader.xhr
      var response = JSON.parse(xhr.responseText)
      if (response.code < 200 || response.code >= 400) {
        data.message = response.message
        evt.cancel()
      } else {
        data.url = response.data.items && response.data.items[0].url || ''
      }
    })
  },
  beforeDestroy: function() {
    this.ckeditor.destroy()
  }
}
</script>
